<script setup>
import HeaderSearch from "@/components/header-search/HeaderSearch.vue"
import ActivityCard from '@/components/activity-card/ScenicCard.vue';
import SharedCard from '@/components/activity-card/sharedCard.vue';
import {computed, ref, watch} from "vue"
import api from "@/api/index.js"
import {useRoute} from 'vue-router'
import {userStore} from '@/stores/user.js'
import {showLoadingToast, closeToast} from "vant"
import {useKeepalive} from "@/hooks/useKeepalive.js"
import {tabInfoStore} from "@/stores/tabInfo.js"


const tabInfo = tabInfoStore();

defineOptions({
  name: 'resultList',
})

const active = '进行中'
const done = '已结束'

const needSaveRoute = ['scenicDetail', 'hotelDetail', 'pandaScenicDetail', 'hotpotDetail']
const {scrollYEle} = useKeepalive(needSaveRoute, 'resultList')

const user = userStore()
const route = useRoute()

const activeTab = ref(active);
const refreshing = ref(false)
const list = ref([])
const totalCount = ref(0)
const loading = ref(false)
const error = ref(false)
const finished = ref(false)
const ordinaryScenicFinished = ref(false)

const onRefresh = () => {
  params.pageNum = 1
  loading.value = true
  onLoad('下拉刷新')
}

let params = {}

const type = ref('')

const placeholder = computed(() => {
  return '请输入活动关键词'
})

const setParams = () => {
  params = {
    pageNum: 1,
    pageSize: 10,
    cityCode: user?.city?.code,
    lon: user.position?.coords?.longitude,
    lat: user.position?.coords?.latitude,
  }

  if (route.query.type === 'activityReservation') {
    params.reservationStatus = 0
  } else {
    tabInfo.setTabVisible(false);
  }
  const {scenicType, classifyId} = route.query
  type.value = route.query.type
  if (scenicType) {
    params.scenicType = scenicType
  }
  if (classifyId) {
    params.scenicTypeCode = classifyId
  }
  if (classifyId === 'all') {
    delete params.scenicTypeCode
  }
}
setParams()


// 获取活动预约列表，先调用的是_getOrdinaryScenicList来显示页面
const _getOrderActivityList = (type) => {
  if (type === 'refresh') {
    params.pageNum = 1
    list.value = []
    ordinaryScenicFinished.value = false;
    finished.value = false;
    loading.value = true;
  }
  ordinaryScenicFinished.value = false
  finished.value = false
  loading.value = true
  api.getActivityReservation(params).then((res) => {
    if (type === '下拉刷新') {
      list.value = []
    }
    list.value = [...list.value, ...res.data.list]
    totalCount.value = res.data.totalCount
    params.pageNum += 1
    if (res.data.currPage===res.data.totalPage || res.data.totalPage===0) {
      ordinaryScenicFinished.value = true
      finished.value = true
    }
    finished.value = res.data.currPage===res.data.totalPage || res.data.totalPage==0
    refreshing.value = false;
    // if(res.data.list.length !== 0){
    //   	loading.value = false
    // }else{
    // 	loading.value = true
    // }
    loading.value = false
  }).catch(() => {
    error.value = true
    loading.value = false
  })
//   .finally(() => {
//     refreshing.value = false
//     closeToast()
//   })
}

// 获取共享预约活动列表
const _getOrderSharedActivityList = (type) => {
  if (type === 'refresh') {
    params.pageNum = 1
    list.value = []
    ordinaryScenicFinished.value = false;
    finished.value = false;
    loading.value = true;
  }
  ordinaryScenicFinished.value = false
  finished.value = false
  loading.value = true
  api.getSharedActivity(params).then((res) => {
    if (type === '下拉刷新') {
      list.value = []
    }
    list.value = [...list.value, ...res.data.list]
    totalCount.value = res.data.totalCount
    params.pageNum += 1
    if (res.data.currPage===res.data.totalPage || res.data.totalPage===0) {
      ordinaryScenicFinished.value = true
      finished.value = true

    }
    refreshing.value = false;
    loading.value = false
    finished.value = res.data.currPage===res.data.totalPage || res.data.totalPage===0;
  }).catch(() => {
    error.value = true
    loading.value = false
  })
}

const filterPandaList = ref([])

const onLoad = (e) => {
  if (type.value === 'activityReservation') {
    _getOrderActivityList(e);
    return;
  }
  // 共享预约
  if (type.value === 'sharedReservation') {
    _getOrderSharedActivityList(e);
    return;
  }
}
onLoad()

watch(error, (val) => {
  if (!val) {
    loading.value = true
    onLoad()
  }
})

const keywords = ref([])
const search = (e) => {
  params = {
    ...params,
    pageNum: 1,
    keyword: e
  }
  if (e) {
    keywords.value = [e]
  } else {
    keywords.value = [];
  }
  onLoad('refresh')
}

const watchChangeCity = ref(0)
const changeCity = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner'
  })
  watchChangeCity.value += 1
  loading.value = true
  onLoad('refresh')
}

</script>

<template>
  <div class="scenic_list_page">
    <div class="filter_search">
      <HeaderSearch
          class="header_search"
          :showIcon="true"
          :placeholder="placeholder"
          @search="search"
          @changeCity="changeCity"
      />
      <img class="scenic_bg" src="@/assets/images/index/scenic_bg.png" alt="">
      <div class='tab-con' v-if="type === 'activityReservation'">
        <div class='tab-for'>
          <div class='tab'
               :class="{'active-tab' : activeTab === active}"
               @click="activeTab = active,params.reservationStatus = 0,list = [],params.pageNum =1,onLoad()"
          >
            <div class='font'>
              进行中
            </div>
            <div class='line'></div>
          </div>
          <div class=tab
               :class="{'active-tab' : activeTab === done}"
               @click="activeTab = done,params.reservationStatus = 1,list = [],params.pageNum =1,onLoad()"
          >
            <div class='font'>
              已结束
            </div>
            <div class='line'></div>
          </div>
        </div>
      </div>
    </div>
    <div class="content" ref="scrollYEle">
      <van-pull-refresh
          class="van_pull_refresh"
          v-model="refreshing"
          @refresh="onRefresh"
      >
        <van-list
            class="scenic_list"
            v-model:loading="loading"
            v-model:error="error"
            :finished="finished"
            finished-text="没有更多了"
            error-text="请求失败，点击重新加载"
            @load="onLoad"
        >
          <template v-if="type === 'activityReservation'">
            <ActivityCard
                class='list'
                v-for="item in list"
                :key="item.id"
                :data="item"
                :keywords="keywords"
            />
          </template>
          <template v-else-if="type === 'sharedReservation'">
            <SharedCard
                class='list'
                v-for="item in list"
                :key="item.id"
                :data="item"
                :keywords="keywords"
            />
          </template>
        </van-list>
        <div v-show="!(list.length || filterPandaList.length) && !loading && !error">
          <div class="none">
            <img class="none_img" src="@/assets/images/index/none1.png" alt="">
            <span>{{ route.query.type === 'activityReservation' ? '暂无活动预约' : '暂无共享预约' }}</span>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped lang="scss">
.scenic_list_page {
  display: flex;
  flex-direction: column;
  height: 100%;

  .filter_search {
    position: relative;

    .tab-con {
      display: flex;
      width: 100%;
      border-radius: 1rem;
      justify-content: center;

      .tab-for {
        align-items: center;
        height: 4rem;
        background: #fff;
        display: flex;
        width: 90%;
        justify-content: space-between;

        .tab {
          margin: 0 10px;
          display: flex;
          flex-wrap: wrap;

          .line {
            width: 100%;
            height: 0.5rem;
            margin-top: 1rem;
          }
        }

        .active-tab {

          .font {
            color: var(--van-tab-active-text-color);
            font-weight: var(--van-font-bold);
          }

          .line {
            width: 100%;
            height: 0.5rem;
            margin-top: 1rem;
            background: linear-gradient(236deg, #ece3aa 0%, #45c89a 100%);
            border-radius: 999px;
          }
        }
      }
    }

    .scenic_bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
    }

    .header_search {
      padding: 1.5rem;
    }
  }

  .content {
    flex: 1;
    overflow-y: auto;

    .van_pull_refresh {
      min-height: 100%;
      background: #F9F8F3;

      .scenic_list {
        //height: 100%;
        //overflow-y: auto;
        .list {
          margin: 1.5rem;
        }
      }

      .none {
        display: flex;
        flex-direction: column;
        align-items: center;

        .none_img {
          width: 6rem;
          margin: 14.4rem 0 1rem 0;
        }

        span {
          font-size: 1.4rem;
          color: #666666;
        }
      }
    }
  }
}
</style>